package ua.kharkov.khpi.tarasenko.bach.core.db;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Calendar;
import java.util.Date;

import org.apache.log4j.Logger;

/**
 * Utilities for working with DB. Providing closing, rolling back and committing
 * connections.
 * 
 * @author oleksandr
 * 
 */
public class DBUtils {
	private static final Logger log = Logger.getLogger(DBUtils.class);

	/**
	 * Rolls back transaction and closing connection.
	 * 
	 * @param conn
	 *            - connection to process.
	 */
	public static void rollBackAndClose(Connection conn) {
		try {
			conn.rollback();
		} catch (SQLException e) {
			log.error("Error occurred during rolling back connection!", e);
		}
		close(conn);
	}

	/**
	 * Commits transaction and closing connection.
	 * 
	 * @param conn
	 *            - connection to process.
	 */
	public static void commitAndClose(Connection conn) {
		try {
			conn.commit();
		} catch (SQLException e) {
			log.error("Error occurred during committing connection!", e);
		}
		close(conn);
	}

	/**
	 * Closes connection.
	 * 
	 * @param conn
	 *            - connection to close.
	 */
	public static void close(Connection conn) {
		try {
			conn.close();
			conn = null;
		} catch (SQLException e) {
			log.warn("Error occurred during closing connection!", e);
		}
	}

	public static void close(ResultSet rs, Statement st) {
		if (log.isTraceEnabled()) {
			log.trace("Close result set and statement.");
		}
		if (rs != null) {
			try {
				rs.close();
				rs = null;
			} catch (SQLException e) {
				log.warn("Cant close result set!", e);
			}
		} else {
			if (log.isTraceEnabled()) {
				log.trace("close(): rs is null.");
			}
		}
		if (st != null) {
			try {
				st.close();
				st = null;
			} catch (SQLException e) {
				log.warn("Cant close statement!", e);
			}
		} else {
			if (log.isTraceEnabled()) {
				log.trace("close(): st is null.");
			}
		}
	}
	
	/**
	 * Converts date from java.sql.Date type to java.util.Date.
	 * 
	 * @param sqlDate
	 *            - date to convert.
	 * @return converted to java.util.Date type.
	 */
	public static java.util.Date convertSqlDateToUtilDate(
			java.sql.Timestamp timestamp) {
		if (log.isTraceEnabled()) {
			log.trace("timestamp is: " + timestamp);
		}
		java.util.Date utilDate = null;
		if (timestamp == null) {
			Calendar c = Calendar.getInstance();
			c.set(Calendar.YEAR, 0, Calendar.MONTH, Calendar.JANUARY,
					Calendar.DAY_OF_MONTH, 1);
			utilDate = c.getTime();
			if (log.isTraceEnabled()) {
				log.trace("created default date: " + utilDate);
			}
		} else {
			utilDate = new Date(timestamp.getTime());
			if (log.isTraceEnabled()) {
				log.trace("converted date is: " + utilDate);
			}
		}
		return utilDate;
	}
}
